package com.latam.arq.example.rules.ejb.impl;

import java.util.Date;

import javax.ejb.Stateless;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.latam.arq.example.domain.ExampleBean;
import com.latam.arq.example.rules.ejb.services.ExampleRuleValidationService;

import de.odysseus.el.ExpressionFactoryImpl;
import de.odysseus.el.util.SimpleContext;

@Stateless(
		name="ExampleRuleValidationEJB",
		description="Example EJB to implemnet dynamic rule validation"
		)
public class ExampleRuleValidationImpl implements ExampleRuleValidationService{
	private static final Logger logger = LoggerFactory.getLogger(ExampleRuleValidationImpl.class);

	public String validateRule( final ExampleBean bean1, final ExampleBean bean2, final String rule ){
		if (logger.isInfoEnabled()){
			logger.info("Validating rule: " + rule);
		}
		
		final ExpressionFactory factory = new ExpressionFactoryImpl();
		final SimpleContext ctx = new SimpleContext();
		
		ctx.setVariable( bean1.getName(), factory.createValueExpression(bean1, ExampleBean.class) );
		ctx.setVariable( bean2.getName(), factory.createValueExpression(bean2, ExampleBean.class) );
		
		ctx.setVariable( "now", factory.createValueExpression( Long.valueOf(System.currentTimeMillis()), Long.class) );
		ctx.setVariable( "actualDate", factory.createValueExpression(new Date(), Date.class) );
		
		//Adding control character for evaluate the rule
		final String localRule = "#{" + rule + "}";
		try{
			final ValueExpression eval = factory.createValueExpression(ctx, localRule, Object.class);
			final Object evalValue = eval.getValue(ctx);
			if (evalValue!=null){
				return evalValue.toString();
			}else{
				return "null";
			}
		}catch(javax.el.ELException e){
			if (logger.isErrorEnabled()){
				logger.error(e.getMessage());
			}
			return e.getMessage();
		}
	}
}
